﻿/*
    顺德报表统计
*/
define("business/statisticalreport", ["leaflet"], function (L) {
    L.DCI.StatisticalReport = L.Class.extend({

        includes: L.Mixin.Events,

        id: "statisticalreport",

        initialize: function () {
            this.selectColor = '#ffb400';
            this.notSelectColor = 'white';
            this.disableColor = '#989595';
            this.filterData = {};
            this.config = Project_ParamConfig.statisticalreport;
        },

        getHtml: function () {
            if (this._hasShow) return;
            this._initSelect();
            this.resLoading = false;
            return this.filterUi();
        },

        init: function () {
            if (this._hasShow) return;
            this._hasShow = true;
            this.filterEvent();
            this._map = L.DCI.App.pool.get("map");
        },

        _initSelect: function () {
            this.filterData = {};
            this._setFilterData('ywlx', this.config.ywlx.item[0]);
        },

        remove: function () {
            $('#' + this.id + '-bg-panel').remove();
            this.filterData = {};
            this._map.activate(L.DCI.Map.StatusType.PAN, null, null, this);
            L.dci.app.util.disableDraw(this._map);
            this._map = null;
            this._hasShow = false;
            this.resLoading = false;
        },

        //构建界面
        filterUi: function () {
            var html = [],
                str = this._filterUi();

            html.push('<div id = "' + this.id + '-bg-panel">');
            html.push(str);
            html.push('</div>');
            return html.join(' ');
        },

        _filterUi: function () {
            var html = [];
            //标题
            html.push('<div id = "' + this.id + '-dqbg" class = "' + this.id + '-dqbg">');
            html.push('<span>统计报表</span>');
            html.push('<span>配建停车指标汇总表</span>');
            html.push('</div>');

            //筛选条件
            html.push('<div id = "' + this.id + '-tjsx" class = "' + this.id + '-tjsx">');

            //业务筛选
            html.push('<div class="' + this.id + '-fasx">');
            html.push('<ul data-tjlx="ywlx">');
            html.push('<li><span>业务类型：</span></li>');
            for (var i = 0; i < this.config.ywlx["item"].length; i++) {
                c = this.isArrHas(this.config.ywlx["item"][i], this.filterData['ywlx'])['has'] ? this.selectColor : this.notSelectColor;
                html.push('<li><span class="can" style="background:' + c + '"  data-bbtj = "ywlx">' + this.config.ywlx["item"][i] + '</span></li>');
            }
            html.push('</ul>');
            html.push('</div>');

            //时间筛选
            html.push('<div class="' + this.id + '-sjsx">');
            html.push('<ul>');
            html.push('<li><span>时间筛选：</span></li>');
            html.push('<li class="select"><button data-cl="nd" class="btn">年度</button></li>');
            html.push('<li><button data-cl="jd" class="btn">季度</button></li>');
            html.push('<li><button data-cl="yd" class="btn">月度</button></li>');
            html.push('</ul>');
            html.push('<div id="' + this.id + '-njy" class="' + this.id + '-njy">');
            html.push('<ul data-tjlx="nd">');
            html.push('<li><span class="line">年度</span></li>');
            for (var i = 0; i < this.config.sjsx.nd["item"].length; i++) {
                html.push('<li><span class="can"  data-bbtj = "nd">' + this.config.sjsx.nd["item"][i] + '</span></li>');
            }
            html.push('</ul>');
            html.push('</div>');
            html.push('</div>');

            //区域筛选
            html.push('<div class="' + this.id + '-qysx">');
            html.push('<ul>');
            html.push('<li><span>区域选择：</span></li>');
            html.push('<li><button data-cl="xzqy" class="btn">行政区域</button></li>');
            html.push('<li><button data-cl="qyhz" class="btn">区域绘制</button></li>');
            html.push('<li><button data-cl="fwxz" class="btn">范围选择</button></li>');
            html.push('</ul>');
            html.push('<div id="' + this.id + '-zqw" class="' + this.id + '-zqw"></div>');
            html.push('</div>');

            //确定
            html.push('<div class="' + this.id + '-qdsx">');
            html.push('<button data-cl="qc" class="btn">重置</button>');
            html.push('<button data-cl="qd" class="btn">确定</button>');
            html.push('</div>');

            html.push('</div>');

            //结果 ？？？
            html.push('<div id = "' + this.id + '-fxjg" class = "' + this.id + '-fxjg">');
            html.push('</div>');

            return html.join(' ');
        },

        //初始化事件
        filterEvent: function () {

            //按钮事件
            $("#" + this.id + "-tjsx").on('click', 'button', $.proxy(function (a) {
                a.stopPropagation();
                var str = $(a.target).data('cl');

                //清除属性选择状态
                this._map.activate(L.DCI.Map.StatusType.PAN, null, null, this);
                L.dci.app.util.disableDraw(this._map);

                if (str == "qd") {
                    if (this.resLoading) return;
                    this.resLoading = true;
                    this.fire('startidentify', {});
                    this.once('identifyed', this._condition);
                    this._executeQu(this.filterData);
                } else if (str == "qc") {
                    this.reset();
                } else {
                    if (true) {
                        $(a.target).parent().siblings().removeClass('select');
                        $(a.target).parent().addClass('select');
                    }
                    this.setSelect(str);
                }
            }, this));

            //条件事件
            $("#" + this.id + "-tjsx").on('click', 'span', $.proxy(this._select, this));
        },

        reset: function () {
            this._initSelect();
            this.resLoading = false;
            this.mapClearHig();

            var str = this._filterUi();
            $('#' + this.id + '-bg-panel').off().html(str);
            this.filterEvent();
        },

        //设置标签页
        setSelect: function (str) {
            var html = [], c, i, j, q, t;

            if (str == "nd") {
                var ul = $('#' + this.id + '-njy').children();
                if (ul.length != 1) ul.last().remove();

            } else if (str == "jd") {
                html.push('<ul data-tjlx="jd">');
                var jd = this.config.sjsx.jd;
                html.push('<li><span class="line">季度</span></li>');
                for (i = 0; i < jd["item"].length; i++) {
                    t = jd["item"][i];
                    c = this.isArrHas(t, this.filterData['jd'])['has'] ? this.selectColor : this.notSelectColor;
                    html.push('<li><span class="can" style="background:' + c + '" data-bbtj = "jd">' + t + '</span></li>');
                }
                html.push('</ul>');

                var div = $('#' + this.id + '-njy');
                var ul = div.children();

                if (ul.length != 1) ul.last().remove();
                div.append(html.join(' '));

            } else if (str == "yd") {
                html.push('<ul data-tjlx="yd">');
                var yd = this.config.sjsx.yd;
                html.push('<li><span class="line">月度</span></li>');
                for (i = 0; i < yd["item"].length; i++) {
                    t = yd["item"][i];
                    c = this.isArrHas(t, this.filterData['yd'])['has'] ? this.selectColor : this.notSelectColor;
                    html.push('<li><span class="can" style="background:' + c + '"  data-bbtj = "yd">' + t + '</span></li>');
                }
                html.push('</ul>');

                var div = $('#' + this.id + '-njy');
                var ul = div.children();

                if (ul.length != 1) ul.last().remove();
                div.append(html.join(' '));

            } else if (str == "xzqy") {
                var xzqj = this.config.xzqj
                var qj, jj;
                var disableC = this.disableColor;
                html.push('<div class="xzqy">')
                html.push('<table>');
                for (i = 0; i < 1; i++) {
                    html.push('<tr>');
                    t = xzqj[i]["name"];
                    html.push('<td rowspan="' + xzqj[i]["item"].length + 1 + '"><span style="color:' + disableC + '" class="line line2">' + t + '</span></td>');
                    for (j = 0; j < xzqj[i]["item"].length; j++) {
                        html.push('<tr>');
                        t = xzqj[i]["item"][j]["name"];
                        html.push('<td ><span style="color:' + disableC + '" class="line">' + t + '</span></td>');

                        var zj = xzqj[i]["item"][j]["item"];
                        html.push('<td>');
                        for (q = 0; q < zj.length; q++) {
                            t = zj[q];
                            c = this.isArrHas(t, this.filterData['zj'])['has'] ? this.selectColor : this.notSelectColor;
                            html.push('<span class="can" style="background:' + c + '" data-bbtj = "zj">' + t + '</span>');
                        }
                        html.push('</td>');
                        html.push('</tr>');
                    }
                    html.push('</tr>');
                }
                html.push('</table>');
                html.push('</div>')
                $('#' + this.id + '-zqw').html(html.join(' '));

            } else if (str == "qyhz") {
                L.dci.app.util.enableDraw(function (o) {

                    this.filterData['polygon'] = o.layer;
                    this.filterData['features'] = null;
                    this.filterData['zj'] = null;

                }, this._map, this, 'polygon', { repeatMode: false });
                $('#' + this.id + '-zqw').html(html.join(' '));

            } else if (str == "fwxz") {
                html.push('<div class="fwxz">');
                html.push('<span class="can" data-bbtj = "fwxz">选择shp</span>');
                html.push('<span class="can" data-bbtj = "fwxz">选择cad</span>');
                html.push('</div>');
                $('#' + this.id + '-zqw').html(html.join(' '));
            }
        },

        //单击选择
        _select: function (a) {
            var parent, target, type, text, has, m, t, m2;

            target = a.target;
            type = $(target).data('bbtj');
            text = target.innerText;

            if (text.indexOf('：') != -1) return;
            if (!type) return;

            //清除属性选择状态
            this._map.activate(L.DCI.Map.StatusType.PAN, null, null, this);
            L.dci.app.util.disableDraw(this._map);

            if (!this.filterData[type]) this.filterData[type] = [];

            if (type == "fwxz") {
                $(target).siblings().css('background', this.notSelectColor);
                $(target).css('background', this.selectColor);
                m2 = m = this._map;
                m.activate(L.DCI.Map.StatusType.SELECT, function (evt) {
                    if (text.indexOf('shp') != -1) { t = 'shp' } else {
                        t = 'cad'
                    }

                    var first = true;
                    this.querySC(t, evt, m2, function () {
                        if (first && (this.filterData['polygon'] || this.filterData['features'])) {
                            first = false;
                            this.mapClearHig();
                            this.filterData['polygon'] = null;
                            this.filterData['features'] = null;
                        }
                        this.filterData['features'] = this.filterData['features'] ? this.filterData['features'].concat(features) : features;
                        this.filterData['zj'] = null;
                    });
                }, null, this);
            } else if (type == "ywlx") {
                has = this.isArrHas(text, this.filterData[type]);
                if (!has.has) {
                    $(target).parent().siblings().children().css('background', this.notSelectColor);
                    $(target).css('background', this.selectColor);
                    this.filterData[type] = [text];
                }
            } else {
                has = this.isArrHas(text, this.filterData[type]);
                if (has.has) {
                    $(target).css('background', this.notSelectColor);
                    this.filterData[type].splice(has.index, 1);
                } else {
                    $(target).css('background', this.selectColor);
                    this.filterData[type].push(text);
                }

                if (type == 'yd') this.filterData['jd'] = null;
                else if (type == 'jd') this.filterData['yd'] = null;
                else if (type == 'zj') {
                    if (this.filterData['features'] || this.filterData['polygon']) {
                        this.mapClearHig();
                        this.filterData['features'] = null;
                        this.filterData['polygon'] = null;
                    }
                }
            }
        },

        _setFilterData: function (type, value) {
            if (!this.filterData[type]) this.filterData[type] = [];
            this.filterData[type].push(value);
        },

        //选择cad shp
        querySC: function (type, evt, map, fn) {
            var layerGroups = null;
            if (type == "shp") {
                layerGroups = map.shpLayerGroups;
            } else if (type == "cad") {
                layerGroups = map.cadLayerGroups;
            }
            for (var i in layerGroups) {
                var layerG = layerGroups[i];
                L.dci.app.util.queryLayerGroup(layerG.group, evt, L.bind(function (features) {
                    fn.call(this, features);
                    this._hightLight(features);
                }, this));
            }
        },

        _hightLight: function (features) {
            for (var i = 0; i < features.length; i++) {
                L.dci.app.util.highLight(this._map, features[i], true, false, "Polygon");
            }
        },

        isArrHas: function (value, array) {
            var has = false, i;
            if (!array || !array.length) return { has: has, index: -1 }
            for (i = 0; i < array.length; i++) {
                if (value == array[i]) {
                    has = true;
                    break;
                }
            }
            return { has: has, index: i };
        },

        //清除高亮图层
        mapClearHig: function () {
            var mapGroup = L.DCI.App.pool.get("SplitScreen").getMapGroup();
            for (var q = 0; q < mapGroup.length; q++) {
                mapGroup[q].getHighLightLayer().clearLayers();
            }
        },

        _getPolyon: function (names, fn) {
            var url = this.config.xzqj[0].url;
            var field = this.config.xzqj[0].field;

            var q = L.esri.Tasks.query(url);


            var str = ""
            for (var i = 0; i < names.length; i++) {
                if (i == 0) str += field + ' like ' + "'%" + names[i] + "%'";
                else str += ' or ' + field + ' like ' + "'%" + names[i] + "%'";
            }
            q.where(str);
            q.run(function (error, featureCollection, response) {
                var g = null;
                if (!error) {
                    var fs = response.features, f = null;

                    for (var i = 0; i < fs.length; i++) {
                        f = L.esri.Util.arcgisToGeojson(fs[i]);
                        if (g) { g.geometry.coordinates = g.geometry.coordinates.concat(f.geometry.coordinates); }
                        else g = f;
                    }
                }
                fn.call(this, g);
            }, this);
        },

        //得出筛选条件
        _executeQu: function (_data) {
            var data = jQuery.extend(true, {}, _data);
            var jz = function (j) {
                if (!j) return null;
                var _jz = {
                    '第一季度': ['1月', '2月', '3月'],
                    '第二季度': ['4月', '5月', '6月'],
                    '第三季度': ['7月', '8月', '9月'],
                    '第四季度': ['10月', '11月', '12月']
                }

                var s = [];
                for (var i = 0; i < j.length; i++) {
                    s = s.concat(_jz[j[i]]);
                }
                return s;
            };
            var year = data['nd'],
                month = data['yd'] || jz(data['jd']),
                business = data['ywlx'];

            var tj = {};
            if (year) tj[this.config['sjsx']['nd']['field']] = year;
            if (month) tj[this.config['sjsx']['yd']['field']] = month;
            if (business) tj[this.config['ywlx']['field']] = business;


            if (data['polygon']) {
                tj.region = data['polygon'].toGeoJSON();
                tj.region = L.dci.app.util.project(tj.region, this._map.getMap().options.crs);
                this.identify(tj);

            } else if (data['features']) {
                var fs = data['features'], f = null, g = null;

                for (var i = 0; i < fs.length; i++) {
                    f = fs[i];
                    if (g) { g.geometry.coordinates = g.geometry.coordinates.concat(f.geometry.coordinates); }
                    else g = f;
                }
                tj.region = g;
                this.identify(tj);

            } else if (data['zj']) {
                this._getPolyon(data['zj'], function (geoJson) {
                    tj.region = geoJson;
                    this.identify(tj);
                });
            } else {
                this.identify(tj);
            }
        },

        boundsToGeoJson: function (bounds) {
            var rec = L.rectangle(bounds);
            rec = rec.toGeoJSON();
            rec = L.dci.app.util.project(rec, this._map.getMap().options.crs);
            return rec;
        },

        //year,month,business,region
        identify: function (options) {
            var sql = [], q, p;
            for (p in options) {
                if (p == "region") continue;
                for (q = 0; q < options[p].length; q++) {
                    sql.push(p + ' like ' + "'%" + options[p][q] + "%'");
                }
            }

            sql = sql.length != 0 ? sql.join(' or ') : null;

            var url = this.config.pjtczb.url,
                layers = this.config.pjtczb.layer.join(','),
                map = this._map.getMap(),
                geometry = options['region'] || this.boundsToGeoJson(this._map.getMap().options['initBounds']);

            var indenty = L.esri.Tasks.identifyFeatures(url);
            indenty.on(map);

            if (sql != null) indenty.layerDef(sql);

            indenty.setGeometry(geometry, false)
                .layers('visible:' + layers)
                .run(function (error, featureCollection, response) {
                    var caseIds = [];
                    if (!error) {
                        this.mapClearHig();
                        for (var i = 0; i < response.results.length; i++) {
                            caseIds.push(response.results[i]['attributes'][this.config.pjtczb['caseId']]);
                            L.dci.app.util.highLight(this._map, response.results[i], true, false, null);
                        }
                    }
                    this.fire('identifyed', { caseIds: caseIds, data: options });
                    this.resLoading = false;
                }, this);
        },

        //显示当前的筛选条件
        _condition: function (data) {
            var nd = data['data'][this.config['sjsx']['nd']['field']],
                yd = data['data'][this.config['sjsx']['yd']['field']],
                yw = data['data'][this.config['ywlx']['field']];
            var html = [];
            html.push('<div class="dqsxtj">');
            html.push('<div class="dqtj">');
            html.push('<div class="trigger">');
            html.push('<span>筛选条件&nbsp;&nbsp;&nbsp;</span>');
            html.push('</div>');

            html.push('<div class="menu-drop">');
            html.push('<ul>');
            if (yw) html.push('<li><span>业务类型:</span>' + yw.join(' ') + '</li>');
            if (nd) html.push('<li><span>年度:</span>' + nd.sort().join('&nbsp;&nbsp;&nbsp;&nbsp;') + '</li>');
            if (yd) html.push('<li><span>月度:</span>' + yd.sort().join('&nbsp;&nbsp;&nbsp;&nbsp;') + '</li>');
            html.push('</ul>')
            html.push('</div>');
            html.push('</div>');
            html.push('<i class="icon-close2"></i>');
            html.push('</div>');

            $('#' + this.id + '-dqbg').append(html.join(' '));
            $('#' + this.id + '-tjsx').remove();
            $('#' + this.id + '-dqbg').one('click', '.icon-close2', $.proxy(function () {
                this.reset();
            }, this));
        }
    });

    L.dci.statisticalreport = function () {
        return new L.DCI.StatisticalReport();
    }
});